`

In this example, we were able to print the variable by using the

${book} syntax within an echo command. This will expand the

book variable to its value.

You can also assign the output of a command to a variable using

the command substitution syntax $(), placing the desired command

between the two parentheses. Youll use this syntax often in bash

programming. Try running the following:

$ root_directory="$(ls -ld /)"

$ echo "${root_directory}"

drwxr-xr-x 1 user user 0 Feb 13 20:12 /

We assign the value of the ls -ld / command to a variable

named root_directory and then use echo to print the output of

the command. In this output, you can see that we were able to get

some metadata about the root directory (/), such as its type and

permission, size, user and group owners, and the timestamp of the

last modification.

Note that you shouldn’t leave whitespace around the assignment

symbol (=) when creating a variable. The following variable

assignment syntax is considered invalid:

book = "this is an invalid variable assignment"

Unassigning Variables

You can unassign assigned variables using the unset command,

as shown here:

$ book="Black Hat Bash"

$ unset book

$ echo "${book}"

Listing 1-9

Unassigning a variable

If you execute these commands in the terminal, no output will be

shown after the echo command executes.

Scoping Variables

Global variables are those available to the entire program. But

variables in bash can also be scoped so that they are only accessible

from within a certain block of code. These variables are called local

variables and are declared using the local keyword. The following

script shows how local and global variables work:

Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks